/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.fill;

import com.wtkj.vo.dzzf.base.kfzx.ObuGoods;
import com.wttech.dzzf.process.dao.FillMissingDataDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import com.wttech.dzzf.process.util.BusinessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 填充obu验收入库信息
 *
 * @author MaShibo
 * @date 2017/12/24.
 */
@Service
public class FillObuGoodsInfosService {

	private static final Logger LOGGER = LoggerFactory.getLogger(FillObuGoodsInfosService.class);

	@Resource
	private FillMissingDataDao fillMissingDataDao;

	@Resource
	private ThreadPoolTaskExecutor executor;

	@Resource
	private TransferUserInfoDao transferUserInfoDao;

	@Resource
	private BaseInfoService baseInfoService;

	private void process() {
		while (true) {
			List<ObuGoods> goodsList = fillMissingDataDao.queryObuGoodsByRow();
			if (CollectionUtils.isEmpty(goodsList)) {
				executor.shutdown();
				LOGGER.info("填充完毕");
				return;
			}
			List<Future<Void>> futures = new ArrayList<>(goodsList.size());
			goodsList.forEach(this::processSingleData);
			baseInfoService.getFutureResult(futures);
		}
	}

	private void processSingleData(ObuGoods obuGoods) {
		try {
			Object obuIdObj = obuGoods.getExtendProperties().get("OBUID");
			String obuId = null;
			if (obuIdObj != null) {
				obuId = obuIdObj.toString();
			}

			String obuNo = obuGoods.getObuNo();
			LOGGER.info("开始处理【{}】", obuNo);
			String goodsId = obuGoods.getId();
			ObuGoods update = new ObuGoods();

			Integer brand = BusinessUtils.determineObuBrand(obuId, obuNo);
			String model = BusinessUtils.determineObuModel(brand, obuNo);

			update.setId(goodsId);
			update.setBrand(brand);
			update.setModel(model);
			transferUserInfoDao.updateDzzfObject(update);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		FillObuGoodsInfosService service = context.getBean(FillObuGoodsInfosService.class);
		service.process();
	}
}
